package org.bonorsoft.modules.system.controller;

import org.apache.commons.io.FileUtils;
import org.apache.shiro.SecurityUtils;
import org.bonorsoft.common.system.vo.LoginUser;
import org.bonorsoft.modules.control.entity.*;
import org.bonorsoft.modules.control.service.*;
import org.bonorsoft.modules.control.util.ZipFileUtil;
import org.bonorsoft.modules.control.util.QrCodeUtils;
import org.bonorsoft.modules.control.vo.QrcodeVo;
import org.bonorsoft.modules.user.entity.SysUserRole;
import org.bonorsoft.modules.user.service.ISysUserRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.bonorsoft.common.api.vo.Result;
import org.bonorsoft.common.aspect.annotation.AutoLog;
import org.bonorsoft.common.system.query.QueryGenerator;
import org.bonorsoft.modules.utils.QrCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.util.List;

@Controller
@RequestMapping("/control/qrcode")
public class DoorQrCodeController {
    @Autowired
    private IAddressService addressService;

    @Autowired
    private IHouseService houseService;

    @Autowired
    private IUnitService unitService;

    @Autowired
    private ISysUserRoleService userRoleService;

    private String prefix = "control/door";

    private static String leader = "09886521b7321506f6e369c2cff65e51";
    private static String admin = "8562594f415f7d7cacfc5d1194585344";
    private static String police = "e5e97f6b870e7e0036072f2df9e9c7d2";

    @GetMapping()
    public String index() {
        return prefix + "/qrcode";
    }

    /**
     * 分页列表查询
     *
     * @param address
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "走访地址-分页列表查询")
    @RequiresPermissions("control:address:list")
    @GetMapping(value = "/list")
    @ResponseBody
    public Result<?> queryPageList(Address address,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<Address> queryWrapper = QueryGenerator.initQueryWrapper(address, req.getParameterMap());
        Page<Address> page = new Page<Address>(pageNo, pageSize);
        IPage<DoorCode> pageList = addressService.pageCode(page, queryWrapper);
        return Result.ok(pageList);
    }

    //生成二维码
    /*@PostMapping("/makeQrcode/{dzbm}")
    @ResponseBody
    public Result<?> makeQrcode(@PathVariable("dzbm") String dzbm, HttpServletRequest request) {
        int qrcode = addressService.countQrcode(dzbm);
        if (qrcode < 1) {
            try {
                String link = "https://www.zhesq.com/control/qrcode/detail";
                String skipLink = link + "/" + dzbm;
                String qrcodeStr = QrCodeUtil.colours(skipLink);
                addressService.insertQrcode(dzbm, qrcodeStr, skipLink);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Result.ok("操作成功！");
    }*/

    //一键生成
    @PostMapping("/makeAllQrcode")
    @ResponseBody
    public Result<?> makeAllQrcode() {
        List<Address> list = addressService.list();
        try {
            for (Address address : list) {
                String dzbm = address.getDzbm();
                String link = "https://www.zhesq.com/control/qrcode/detail";
                String skipLink = link + "/" + dzbm;
                String qrcodeStr = QrCodeUtil.colours(skipLink);
                addressService.insertQrcode(dzbm, qrcodeStr, skipLink);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.ok("操作成功！");
    }

    @GetMapping("/detail/{dzbm}")
    public String detail(@PathVariable("dzbm") String dzbm, ModelMap map) {

        Address address = addressService.getById(dzbm);
        int build_count = houseService.count(new QueryWrapper<House>().eq("dzbm", dzbm));
        int unit_count = unitService.count(new QueryWrapper<Unit>().eq("dwdz_dzbm", dzbm));
        if (build_count > 0) {
            House house = houseService.getOne(new QueryWrapper<House>().eq("dzbm", dzbm));
            map.put("house", house);
            try {
                boolean access = false;
                LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();//取得当前用户
                List<SysUserRole> userRoles = userRoleService.selectUserRoleByUserId(user.getId());
                for (SysUserRole userRole : userRoles) {
                    String roleId = userRole.getId();
                    if (roleId.equals(leader) || roleId.equals(admin) || roleId.equals(police)) {
                        access = true;
                    }
                }
                if (house.getFzLxdh().equals(user.getPhone()) || access) {
                    return prefix + "/houseAdminDetail";
                } else {
                    return prefix + "/houseDetail";
                }
            } catch (Exception e) {
                return prefix + "/houseDetail";
            }
        } else if (unit_count > 0) {
            Unit unit = unitService.getOne(new QueryWrapper<Unit>().eq("dwdz_dzbm", dzbm));
            map.put("unit", unit);
            try {
                boolean access = false;
                LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();//取得当前用户
                List<SysUserRole> userRoles = userRoleService.selectUserRoleByUserId(user.getId());
                for (SysUserRole userRole : userRoles) {
                    String roleId = userRole.getId();
                    if (roleId.equals(leader) || roleId.equals(admin) || roleId.equals(police)) {
                        access = true;
                    }
                }
                if (unit.getLxdh().equals(user.getPhone()) || unit.getFddbrLxdh().equals(user.getPhone()) || access) {
                    return prefix + "/unitAdminDetail";
                } else {
                    return prefix + "/unitDetail";
                }
            } catch (Exception e) {
                return prefix + "/unitDetail";
            }

        } else {
            map.put("address", address);
            return prefix + "/detail";
        }
    }

    //查看二维码
    @GetMapping("/seeQrcode/{dzbm}")
    public String seeQrcode(@PathVariable("dzbm") String dzbm, ModelMap map) {
        String qrcode = addressService.getQrcode(dzbm);
        String dzmc = addressService.getOne(new QueryWrapper<Address>().eq("dzbm", dzbm)).getDzmc();
        map.put("qrcode", qrcode);
        map.put("dzmc", dzmc);
        return prefix + "/seeQrcode";
    }

    //一键下载(服务器)
    @PostMapping("/downloadAllQcode")
    @ResponseBody
    public Result<?> downloadAllQcode() {
        List<QrcodeVo> list = addressService.getAllQrcode();
        try {
            for (QrcodeVo qrcodeVo : list) {
                File qrcFile = new File("C:\\police\\upFiles\\qrcode\\" + qrcodeVo.getDzmc() + ".jpg");
                String qrCodeContent = qrcodeVo.getQrcode();
                String pressText = qrcodeVo.getDzmc();
                QrCodeUtils.generateQrCode(qrcFile, qrCodeContent, pressText);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.ok("操作成功！");
    }


    //下载压缩包
    @PostMapping("/download/zip")
    @ResponseBody
    public void packager(HttpServletResponse response) {

    }
    /*@PostMapping("/downloadZip")

    public void downloadFile(HttpServletRequest request, HttpServletResponse response, @RequestParam(name="ids",required=true) String ids) throws Exception {
        response.setContentType("APPLICATION/OCTET-STREAM");
        response.setHeader("Content-Disposition", "attachment; filename=" + "export.zip");
        ZipFileUtil zipFileUtil = new ZipFileUtil();
        zipFileUtil.qrcodeZip(ids,response.getOutputStream());

        // 输出到客户端
        OutputStream out = null;
        out = response.getOutputStream();
        response.reset();
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(zipFileName.getBytes("GB2312"), "ISO-8859-1"));
        response.setContentType("application/octet-stream; charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        out.write(FileUtils.readFileToByteArray(zipFile));
        out.flush();
        out.close();

        // 输出客户端结束后，删除压缩包
        if (zipFile.exists()) {
            zipFile.delete();
        }
    }*/

}
